package com.shebei.api.equipment_api_test.job;


import cn.hutool.extra.mail.MailUtil;
import com.shebei.api.equipment_api_test.model.responseModel.ResCount;
import com.shebei.api.equipment_api_test.utils.GetConfig;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Date;
import java.util.Properties;

@Component
public class SendMail {

    private final static Logger loger = LoggerFactory.getLogger(MailUtil.class) ;
    public static String myEmailAccount="radar@uni-ubi.com";
    public static String myEmailPassword="Test12345";
    public static String myEmailSMTPHost="smtp.exmail.qq.com";

    //收件人邮箱
    //"平台中心-平台测试部"<ptcs@uni-ubi.com>;
    public  String receiveMailAccount= GetConfig.getAddress("receiveMailAccount");

    public void send(ResCount resCount,String receiveMailAccounts) throws Exception {
        Properties props=new Properties();
        props.setProperty("mail.transport.protocol","smtp"); //设置使用的协议为smtp
        props.setProperty("mail.smtp.host",myEmailSMTPHost); //设置smtp服务器地址
        props.setProperty("mail.smtp.auth","true");  //需要请求认证
          //创建会话，用于和邮件服务器交互
        Session session=Session.getInstance(props);
        session.setDebug(true);
       if(receiveMailAccounts==null){
           receiveMailAccounts=receiveMailAccount;
       }
        //创建一封邮件
        MimeMessage message=createMimeMessage(session, myEmailAccount, receiveMailAccounts,resCount);

        //根据session 获取邮件传输对象
        Transport transport=session.getTransport();

        transport.connect(myEmailAccount,myEmailPassword);

        transport.sendMessage(message,message.getAllRecipients());

        transport.close();
    }

    private   MimeMessage  createMimeMessage(Session session,String sendMail,String receiveMail,ResCount resCount) throws Exception{

        //创建一封邮件
        MimeMessage message=new MimeMessage(session);
        String reportName=resCount.getReportName();
        //from :发件人
        message.setFrom(new InternetAddress(sendMail, reportName, "UTF-8"));


//        message.setFrom(new InternetAddress(fromMail)); // 设置发件人的地址 多人
//        InternetAddress[] sendTo = new InternetAddress[toMailArr.length];
//        for (int i = 0; i < toMailArr.length; i++) {
//            sendTo[i] = new InternetAddress(toMailArr[i], fromName);
//        }

        //to 收件人

        InternetAddress[] carbonCopy = InternetAddress.parse(receiveMail);

        message.setRecipients(MimeMessage.RecipientType.TO, carbonCopy);

        //邮件主题

        message.setSubject(resCount.getReportName(), "UTF-8");

        //邮件正文
        Multipart content=getContents(resCount);
        message.setContent(content);

       //发送时间
        message.setSentDate(new Date());

        //保存设置
        message.saveChanges();

        return message;

    }


    private Multipart getContents(ResCount resCount){

        BodyPart mdp=new MimeBodyPart(); //新建一个存放信件内容的BodyPart对象

        Multipart mm=new MimeMultipart();//新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)
        try {
            String content=getContent(resCount);
            mdp.setContent(content,"text/html;charset=UTF-8");//给BodyPart对象设置内容和格式/编码方式
            mm.addBodyPart(mdp);//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        return mm;


    }


    private String readHtmlToString() throws Exception{

        InputStream is =null;
        Reader reader = null;

        try {
            is = MailUtil.class.getClassLoader().getResourceAsStream("templates/mailTemplateNew.html");
            if(is ==null){
                throw new Exception("未找到模版文件");
            }

            reader = new InputStreamReader(is, "UTF-8");
            StringBuffer sb=new StringBuffer();
            int bufferSize=1024;
            char[] buffer=new char[bufferSize];
            int length=0;
            while((length=reader.read(buffer,0,bufferSize))!=-1){
                sb.append(buffer,0,length);
            }
            return sb.toString();
        } finally {
            try {
                if(is!=null){
                    is.close();
                }
            }catch (IOException e){
                loger.error("关闭io流异常",e);
            }

            try {
                if(reader!=null){
                    reader.close();
                }
            }catch (IOException e){
                loger.error("关闭IO流异常",e);
            }
        }
    }


    public String getContent(ResCount resCount){
        try {

            //"<font color=red>运行结果为=" + iter.getExcuteResult() + "</font>\n<br/>"
            String excuteRes="总执行用例数为:"+resCount.getTotal()+";成功数为:"+resCount.getSuccess()+"；"+ "<font color=red>失败用例=" + resCount.getFailed() + "</font>\n<br/>";
            String html=readHtmlToString();
            //写入模版内容
            Document doc= Jsoup.parse(html);
            doc.getElementById("title").html(resCount.getReportName()+"报告");
            doc.getElementById("content").html(excuteRes);
            doc.getElementById("detials").html(resCount.getDetailReport());

            return  doc.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
